//
//  WBNetworkManager+Extension.swift
//  仿新浪微博
//
//  Created by 罗超 on 2017/8/17.
//  Copyright © 2017年 LuoChao. All rights reserved.
//

import Foundation

// 封装本项目的网络请求方法
extension WBNetworkManager {
    
    /// 加载项目数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0。
    /// - Parameter completion: 完成回调 [list: 字典数组/是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: AnyObject]]?, _ isSuccess: Bool)->()) {
        
        // 请求数据
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": since_id,
                      "max_id": max_id>0 ? max_id-1 : 0]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            //取数据
            guard let result = json as? [String: AnyObject],
                let list = result["statuses"] as? [[String: AnyObject]] else {
                    print("statusList - 数据出错了")
                    return
            }
            completion(list, isSuccess)
        }
    }
    
    /// 返回微博的未读数量
    func unreadCount(completion: @escaping (_ count: Int)->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            completion(count ?? 0)
        }
    }
}

// MARK: - OAuth相关方法
extension WBNetworkManager {
    /// 加载 AccessToken
    func loadAccessToken(code: String) {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": WBAppKey,
                      "client_secret": WBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WBRedirectURI,]
        
        request(method: .POST, URLString: urlStr, parameters: params) { (json, isSuccess) in
            // 用字典设置属性
            self.userAccount.yy_modelSet(withJSON: json as Any)
            // 保存模型
            self.userAccount.saveAccount()
        }
    }
}
